#include "opencvrenderthread.h"
#include "QDebug"
cv::VideoCapture capture;

void OpenCVRenderThread::open(int index_id)
{
    close();
    capture.open(index_id);
}

void OpenCVRenderThread::close()
{
    capture.release();
}

void OpenCVRenderThread::render()
{
    usleep(1000000/20);
    if(isPause) return;
    // OpenCV
    cv::Mat matTmp;
    if(capture.read(matTmp)){
        if(!matTmp.empty()){
            QImage image=Mat2QImage(matTmp);
            emit in_update_window_thread(image);
        }
    }
    cv::waitKey(1);
}

// 格式转换： cv::Mat 转 QImage
QImage OpenCVRenderThread::Mat2QImage(const cv::Mat &mat)
{
    switch (mat.type())
    {
    // 8-bit, 4 channel
    case CV_8UC4:
    {
        QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_ARGB32);
        return image;
    }
        // 8-bit, 3 channel
    case CV_8UC3:
    {
        QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_RGB888);
        return image.rgbSwapped();
    }
        // 8-bit, 1 channel
    case CV_8UC1:
    {
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
        QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_Grayscale8);
#else
        static QVector<QRgb>  sColorTable;
        // only create our color table the first time
        if (sColorTable.isEmpty())
        {
            sColorTable.resize( 256 );

            for ( int i = 0; i < 256; ++i )
            {
                sColorTable[i] = qRgb( i, i, i );
            }
        }

        QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_Indexed8 );
        image.setColorTable(sColorTable);
#endif
        return image;
    }
        // wrong
    default:
        // qDebug() << "ERROR: Mat could not be converted to QImage.";
        break;
    }
    return QImage();
}
